<template>
  <div class="collects-view">
    <div class="page-header">
      <h1>我的收藏</h1>
      <p>管理你收藏的心仪商品</p>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="action-left">
        <el-checkbox 
          v-model="selectAll" 
          :indeterminate="isIndeterminate"
          @change="handleSelectAll"
        >
          全选
        </el-checkbox>
        <span class="selected-count">
          已选择 {{ selectedItems.length }} 项
        </span>
      </div>
      
      <div class="action-right">
        <el-button
          v-if="selectedItems.length > 0"
          type="danger"
          :icon="Delete"
          @click="batchRemoveCollect"
        >
          批量取消收藏
        </el-button>
        <el-button
          :icon="Refresh"
          @click="refreshCollects"
          :loading="isLoading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 收藏列表 -->
    <div class="collects-content">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <!-- 收藏商品网格 -->
      <div v-else-if="collectsList.length > 0" class="collects-grid">
        <div 
          v-for="item in collectsList" 
          :key="item.goodsId"
          class="collect-item"
          :class="{ selected: selectedItems.includes(item.goodsId) }"
        >
          <div class="item-checkbox">
            <el-checkbox 
              :model-value="selectedItems.includes(item.goodsId)"
              @change="toggleSelect(item.goodsId)"
            />
          </div>
          
          <GoodsCard :goods="item" />
          
          <div class="item-actions">
            <el-button
              type="danger"
              :icon="Delete"
              size="small"
              @click="removeCollect(item.goodsId)"
            >
              取消收藏
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="暂无收藏商品">
          <template #image>
            <div class="empty-icon">⭐</div>
          </template>
          <el-button type="primary" @click="$router.push('/')">
            去首页看看
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 分页 -->
    <Pagination
      v-if="collectsList.length > 0"
      :total="pagination.total"
      :page="pagination.page"
      :limit="pagination.limit"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { collectApi } from '@/api/collect'
import { ElMessage, ElMessageBox } from 'element-plus'
import GoodsCard from '@/components/GoodsCard.vue'
import Pagination from '@/components/Pagination.vue'
import { 
  Delete, 
  Refresh 
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 收藏列表数据
const collectsList = ref([])
const isLoading = ref(false)
const pagination = ref({
  page: 1,
  limit: 20,
  total: 0
})

// 选择相关
const selectedItems = ref([])
const selectAll = ref(false)

// 是否为半选状态
const isIndeterminate = computed(() => {
  const selectedCount = selectedItems.value.length
  return selectedCount > 0 && selectedCount < collectsList.value.length
})

// 获取收藏列表
const getCollectsList = async () => {
  try {
    isLoading.value = true
    const response = await collectApi.getCollectList({
      page: pagination.value.page,
      limit: pagination.value.limit
    })
    
    if (response.code === 200) {
      collectsList.value = response.data.list
      pagination.value.total = response.data.total
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
  } finally {
    isLoading.value = false
  }
}

// 全选/取消全选
const handleSelectAll = (checked) => {
  if (checked) {
    selectedItems.value = collectsList.value.map(item => item.goodsId)
  } else {
    selectedItems.value = []
  }
}

// 切换单个选择
const toggleSelect = (goodsId) => {
  const index = selectedItems.value.indexOf(goodsId)
  if (index > -1) {
    selectedItems.value.splice(index, 1)
  } else {
    selectedItems.value.push(goodsId)
  }
  
  // 更新全选状态
  selectAll.value = selectedItems.value.length === collectsList.value.length
}

// 取消单个收藏
const removeCollect = async (goodsId) => {
  try {
    await ElMessageBox.confirm('确定要取消收藏这个商品吗？', '确认操作', {
      type: 'warning'
    })
    
    const response = await collectApi.removeCollect(goodsId)
    if (response.code === 200) {
      ElMessage.success('已取消收藏')
      // 从列表中移除
      collectsList.value = collectsList.value.filter(item => item.goodsId !== goodsId)
      // 从选中列表中移除
      const index = selectedItems.value.indexOf(goodsId)
      if (index > -1) {
        selectedItems.value.splice(index, 1)
      }
      // 更新总数
      pagination.value.total--
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 批量取消收藏
const batchRemoveCollect = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要取消收藏的商品')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要取消收藏选中的 ${selectedItems.value.length} 个商品吗？`,
      '批量操作确认',
      { type: 'warning' }
    )
    
    const response = await collectApi.batchRemoveCollect(selectedItems.value)
    if (response.code === 200) {
      ElMessage.success('批量取消收藏成功')
      // 刷新列表
      await getCollectsList()
      // 清空选择
      selectedItems.value = []
      selectAll.value = false
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量取消收藏失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 刷新收藏列表
const refreshCollects = () => {
  selectedItems.value = []
  selectAll.value = false
  getCollectsList()
}

// 处理分页
const handlePageChange = (page) => {
  pagination.value.page = page
  getCollectsList()
}

const handleSizeChange = (size) => {
  pagination.value.limit = size
  pagination.value.page = 1
  getCollectsList()
}

// 组件挂载时获取数据
onMounted(() => {
  getCollectsList()
})
</script>

<style scoped>
.collects-view {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  font-size: 16px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.action-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.selected-count {
  color: #666;
  font-size: 14px;
}

.action-right {
  display: flex;
  gap: 10px;
}

.collects-content {
  margin-bottom: 30px;
}

.loading-container {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.collects-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.collect-item {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.collect-item.selected {
  ring: 2px solid #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.item-checkbox {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  padding: 4px;
  backdrop-filter: blur(10px);
}

.item-actions {
  position: absolute;
  bottom: 10px;
  right: 10px;
  z-index: 10;
}

.empty-state {
  background: white;
  padding: 60px 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .action-left,
  .action-right {
    justify-content: center;
  }
  
  .collects-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 15px;
  }
}

@media (max-width: 480px) {
  .collects-grid {
    grid-template-columns: 1fr;
  }
}
</style>